<!-- src/views/pages/MaterialManage.vue -->
<template>
  <div class="material-manage">
    <!-- 顶栏 -->
    <TopBar />

    <!-- 内容区域 -->
    <div class="content">
      <!-- 菜单 -->
      <MenuLine />

      <!-- 操作栏 -->
      <div class="operation-bar">
        <el-button type="primary" @click="openAddDialog">添加物资</el-button>
      </div>

      <!-- 物资列表 -->
      <el-table :data="materialList" style="width: 100%" border v-loading="loading">
        <el-table-column prop="id" label="ID" width="100" />
        <el-table-column prop="materialNumber" label="物资编号" width="150" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="typeName" label="类型" width="150" />
        <el-table-column prop="warehouseName" label="仓库" width="150" /> <!-- 新增 -->
        <el-table-column prop="quantity" label="数量" width="120" />
        <el-table-column prop="status" label="状态" width="150">
          <template #default="{ row }">
            {{ statusMap[row.status] || row.status }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="250" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="openEditDialog(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteMaterial(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加/编辑弹窗 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="30%"
        @close="resetForm"
      >
        <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
          <el-form-item
            v-for="field in materialFields"
            :key="field.key"
            :label="field.label"
            :prop="field.key"
          >
            <el-input
              v-if="field.type === 'text'"
              v-model="form[field.key]"
              :placeholder="field.placeholder"
              :maxlength="field.maxLength"
            />
            <el-input
              v-if="field.type === 'number'"
              v-model.number="form[field.key]"
              type="number"
              :placeholder="field.placeholder"
              :min="0"
            />
            <el-select
              v-else-if="field.type === 'select'"
              v-model="form[field.key]"
              :placeholder="field.placeholder"
              style="width: 100%"
              :disabled="!field.options || !field.options.length"
            >
              <el-option
                v-for="option in field.options"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
              <el-option v-if="!field.options || !field.options.length" disabled label="无可用选项" :value="0" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :disabled="!materialTypeOptions.length || !warehouseOptions.length">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { useMaterialStore, materialFields, type Material } from '@/stores/material';
import { useMaterialTypeStore } from '@/stores/materialType';
import { useWarehouseStore } from '@/stores/warehouse'; // 新增
import TopBar from '@/components/TopBar.vue';
import MenuLine from '@/components/MenuLine.vue';

// 物资、物资类型和仓库 store
const materialStore = useMaterialStore();
const materialTypeStore = useMaterialTypeStore();
const warehouseStore = useWarehouseStore(); // 新增
const materialList = ref<Material[]>([]);
const loading = ref(false);

// 物资类型、仓库和状态选项
const materialTypeOptions = ref<{ value: number; label: string }[]>([]);
const warehouseOptions = ref<{ value: number; label: string }[]>([]); // 新增
const statusOptions = ref([
  { value: 'AVAILABLE', label: '可用' },
  { value: 'LOW_STOCK', label: '低库存' },
  { value: 'OUT_OF_STOCK', label: '缺货' },
]);
const statusMap = {
  AVAILABLE: '可用',
  LOW_STOCK: '低库存',
  OUT_OF_STOCK: '缺货',
};

// 跟踪已提醒的低库存物资
const warnedMaterials = new Set<number>();

// 动态更新 materialFields 的选项
materialFields.find(f => f.key === 'typeId')!.options = materialTypeOptions.value;
materialFields.find(f => f.key === 'warehouseId')!.options = warehouseOptions.value; // 新增
materialFields.find(f => f.key === 'status')!.options = statusOptions.value;

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref('添加物资');
const isEdit = ref(false);
const form = ref<Material>({
  id: 0,
  materialNumber: '',
  name: '',
  typeId: 0,
  typeName: '',
  warehouseId: 0, // 新增
  warehouseName: '', // 新增
  quantity: 0,
  status: '',
  createTime: '',
});
const formRef = ref<FormInstance>();

// 表单校验规则
const rules = ref<FormRules>({
  materialNumber: [
    { required: true, message: '请输入物资编号', trigger: 'blur' },
    { pattern: /^M\d{3}$/, message: '物资编号格式为 M+3位数字（如 M001）', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { min: 1, max: 50, message: '名称长度在 1 到 50 字符', trigger: 'blur' },
  ],
  typeId: [
    { required: true, message: '请选择物资类型', trigger: 'change' },
    { type: 'number', min: 1, message: '请选择有效的物资类型', trigger: 'change' },
  ],
  warehouseId: [ // 新增
    { required: true, message: '请选择仓库', trigger: 'change' },
    { type: 'number', min: 1, message: '请选择有效的仓库', trigger: 'change' },
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '数量不能为负', trigger: 'blur' },
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' },
  ],
});

// 获取物资类型选项
const fetchMaterialTypes = async () => {
  try {
    const types = await materialTypeStore.fetchMaterialTypes();
    materialTypeOptions.value = types.map(type => ({
      value: type.id,
      label: type.name,
    }));
    materialFields.find(f => f.key === 'typeId')!.options = materialTypeOptions.value;
    console.log('物资类型选项:', materialTypeOptions.value);
  } catch (error) {
    ElMessage.error('获取物资类型列表失败');
    console.error('物资类型加载失败:', error);
  }
};

// 获取仓库选项
const fetchWarehouses = async () => {
  try {
    const warehouses = await warehouseStore.fetchWarehouses();
    warehouseOptions.value = warehouses.map(warehouse => ({
      value: warehouse.id,
      label: warehouse.name,
    }));
    materialFields.find(f => f.key === 'warehouseId')!.options = warehouseOptions.value;
    console.log('仓库选项:', warehouseOptions.value);
  } catch (error) {
    ElMessage.error('获取仓库列表失败');
    console.error('仓库加载失败:', error);
  }
};

// 获取物资列表并检查低库存
const fetchMaterials = async () => {
  loading.value = true;
  try {
    const result = await materialStore.fetchMaterials();
    materialList.value = result.map(material => ({
      ...material,
      typeName: materialTypeOptions.value.find(opt => opt.value === material.typeId)?.label || material.typeName || '未知类型',
      warehouseName: warehouseOptions.value.find(opt => opt.value === material.warehouseId)?.label || material.warehouseName || '未知仓库', // 新增
    }));
    // 检查低库存
    const LOW_STOCK_THRESHOLD = 50;
    materialList.value.forEach(material => {
      if (material.quantity <= LOW_STOCK_THRESHOLD && !warnedMaterials.has(material.id)) {
        ElMessage.warning(`物资 ${material.name} 数量不足，仅剩 ${material.quantity} 单位！`);
        warnedMaterials.add(material.id);
      }
    });
    console.log('物资列表:', materialList.value);
  } catch (error) {
    ElMessage.error('获取物资列表失败');
    console.error('物资加载失败:', error);
  } finally {
    loading.value = false;
  }
};

// 打开添加弹窗
const openAddDialog = async () => {
  isEdit.value = false;
  dialogTitle.value = '添加物资';
  await Promise.all([fetchMaterialTypes(), fetchWarehouses()]); // 新增仓库
  form.value = {
    id: 0,
    materialNumber: '',
    name: '',
    typeId: materialTypeOptions.value[0]?.value || 0,
    typeName: materialTypeOptions.value[0]?.label || '',
    warehouseId: warehouseOptions.value[0]?.value || 0, // 新增
    warehouseName: warehouseOptions.value[0]?.label || '', // 新增
    quantity: 0,
    status: statusOptions.value[0]?.value || 'AVAILABLE',
    createTime: '',
  };
  dialogVisible.value = true;
};

// 打开编辑弹窗
const openEditDialog = async (row: Material) => {
  isEdit.value = true;
  dialogTitle.value = '编辑物资';
  await Promise.all([fetchMaterialTypes(), fetchWarehouses()]); // 新增仓库
  form.value = {
    ...row,
    typeName: materialTypeOptions.value.find(opt => opt.value === row.typeId)?.label || row.typeName,
    warehouseName: warehouseOptions.value.find(opt => opt.value === row.warehouseId)?.label || row.warehouseName, // 新增
  };
  dialogVisible.value = true;
};

// 提交表单（添加或编辑）
const submitForm = async () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const type = materialTypeOptions.value.find(opt => opt.value === form.value.typeId);
        const warehouse = warehouseOptions.value.find(opt => opt.value === form.value.warehouseId); // 新增
        const payload = {
          ...form.value,
          typeName: type ? type.label : form.value.typeName || '未知类型',
          warehouseName: warehouse ? warehouse.label : form.value.warehouseName || '未知仓库', // 新增
        };
        if (isEdit.value) {
          await materialStore.updateMaterial(payload);
          ElMessage.success('编辑物资成功');
        } else {
          await materialStore.createMaterial({
            materialNumber: form.value.materialNumber,
            name: form.value.name,
            typeId: form.value.typeId,
            warehouseId: form.value.warehouseId, // 新增
            quantity: form.value.quantity,
            status: form.value.status,
          });
          ElMessage.success('添加物资成功');
        }
        dialogVisible.value = false;
        await fetchMaterials();
      } catch (error: any) {
        const errorMessage = error.response?.data?.message || (isEdit.value ? '编辑物资失败' : '添加物资失败');
        ElMessage.error(errorMessage);
        console.error('提交失败:', error, error.response?.data);
      }
    }
  });
};

// 删除物资
const deleteMaterial = async (id: number) => {
  ElMessageBox.confirm('确定删除该物资吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await materialStore.deleteMaterial(id);
        ElMessage.success('删除物资成功');
        warnedMaterials.delete(id); // 移除已删除物资的提醒
        await fetchMaterials();
      } catch (error: any) {
        const errorMessage = error.response?.data?.message || '删除物资失败';
        ElMessage.error(errorMessage);
        console.error('删除失败:', error, error.response?.data);
      }
    })
    .catch(() => {
      ElMessage.info('取消删除');
    });
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.value = {
    id: 0,
    materialNumber: '',
    name: '',
    typeId: 0,
    typeName: '',
    warehouseId: 0, // 新增
    warehouseName: '', // 新增
    quantity: 0,
    status: '',
    createTime: '',
  };
};

// 初始化加载
onMounted(async () => {
  await Promise.all([fetchMaterialTypes(), fetchWarehouses()]);
  await fetchMaterials();
});
</script>

<style scoped>
.material-manage {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content {
  padding-top: 60px;
  width: 80%;
  margin: 0 auto;
  padding-bottom: 60px;
}

.operation-bar {
  margin: 20px 0;
}

.el-table {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>